<?php
/**
 * Created by PhpStorm.
 * User: zcq
 * Date: 2018/10/17
 * Time: 9:21
 */

namespace app\common;


use think\Exception;

class RedisCache
{
    public $host ;
    public $port;
    public $auth;
    public $db;
    public $redis;
    static private $instance;

    private function __construct()
    {
        $this->host = env('REDIS_HOST','127.0.0.1');
        $this->port = env('REDIS_PORT',3306);
        $this->auth = env('REDIS_PASSWORD','');
        $this->db = env('REDIS_DB',0);
        $this->redis = new \Redis();
        $this->connect();
    }

    public static function getInstance()
    {
        if(!isset(self::$instance)){
            self::$instance = new static();
        }
        return self::$instance;
    }

    private function connect()
    {
        try{
            $this->redis->connect($this->host,$this->port);
        }catch (\RedisException $exception){
            $this->redis = false;
            return ;
        }
        if($this->auth){
            $this->redis->auth($this->auth);
        }
        $this->redis->select($this->db);
        return $this;
    }

    public function cache($key,$value='',$time=0)
    {
        if(!$this->redis)
            return false;
        if($value && $time>0){
            return $this->redis->setex($key,$time,$value);
        }elseif($value){
            return $this->redis->set($key,$value);
        }elseif($value===''){
            return $this->redis->get($key);
        }elseif(is_null($value)){
            return $this->redis->del($key);
        }
    }

    public function hashGet($key,$field = '')
    {
        if(!$this->redis)
            return false;
        if(is_array($field)){
            return $this->redis->hMGet($key,$field);
        }elseif($field){
            return $this->redis->hGet($key,$field);
        }else{
            return $this->redis->hGetAll($key);
        }

    }

    public function hashSet($key,$field = '',$value = '')
    {
        //暂不支持一次对多个field删除
        if(!$this->redis)
            return false;

        if (is_array($field)){
            return $this->redis->hMSet($key,$field);
        }elseif ($field && $value){
            return $this->redis->hSet($key,$field,$value);
        }elseif( $field && $value===null){
            return $this->redis->hDel($key,$field);
        }elseif ($field === null){
            return $this->redis->delete($key);
        }
        return false;
    }

    public function empty_redis()
    {
        //暂不支持一次对多个field删除
        if(!$this->redis)
            return false;
        return $this->handler('FLUSHDB',$this->db);
    }


    /**
     * @param $method redis方法名称
     * @param $key
     * @param mixed ...$arg
     * @return bool
     * 手动调用redis方法
     */
    public function handler($method,$key,...$arg)
    {
        if(!$this->redis)
            return false;
        return $this->redis->$method($key,...$arg);
    }
}